<template>
  <setting-public-view
    current="eventType"
    view-class="setting-view-main2 service-event-container"
    :nav="eventNav"
  >
    <!-- 服务事件头部 -->
    <div class="service-event-header">
      <div>
        <h2>
          {{$t('event.setting.serviceEventTypeSetting.manage.title1')}}
          <el-tooltip trigger="hover">
            <div slot="content">
              <span>{{$t('event.setting.serviceEventTypeSetting.manage.tips1', {data1:maxEventTypeNum})}}</span>
            </div>
            <i class="el-icon-question" />
          </el-tooltip>
        </h2>
        <p>
          {{$t('event.setting.serviceEventTypeSetting.manage.tips2')}}
        </p>
      </div>
      <div class="lh-52">
        <el-button type="primary" @click="addEventType">
          <i class="iconfont icon-add2" style="font-size: 12px;"></i>{{$t('common.base.create')}}
        </el-button>
      </div>
    </div>

    <!-- 服务事件列表 -->
    <div class="service-event-list" v-loading="loading">
      <draggable
        v-bind="{ animation: 380, ghostClass: 'ghost' }"
        v-model="serviceEventTypeList"
        tag="div"
        @change="updateListOrder"
        class="service-event-group"
      >
        <service-event-item
          class="service-event-item"
          v-for="(item, index) in serviceEventTypeList"
          :key="index"
          :service-event="item"
          :enable-type-num="enableTypeNum"
          :max-type-num="maxEventTypeNum"
          @updateAttr="updateEventItemType($event, item)"
          @update="getServiceEventList"
          @handleChooseUseDept="handleChooseUseDept(item)"
        ></service-event-item>
      </draggable>
    </div>

    <!-- 新增服务事件弹窗 -->
    <add-service-event-dialog
      :visiable.sync="isAddEventTypeModal"
      :service-event-type-list="serviceEventTypeList"
    ></add-service-event-dialog>


    <choose-team-confirm-dialog type="event" @submit="handleChangeUseDept" ref="chooseTeamConfirmDialog" />

  </setting-public-view>
</template>

<script>
/** component */
import draggable from 'vuedraggable';
import SettingPublicView from '@src/modules/setting/components/settingPublicView';
import ServiceEventItem from './components/ServiceEventItem.vue';
import AddServiceEventDialog from './components/AddServiceEventDialog.vue';
import ChooseTeamConfirmDialog from './components/ChooseTeamConfirmDialog/ChooseTeamConfirmDialog'; 
/** mock */
import eventTypeListRes from '../mock/serviceEventList';
/** api */
import {
  getEventTypeList,
  orderWithEventTypeList,
} from '@src/api/SettingServiceEventApi';
/** until */
import { eventNav } from '@src/modules/setting/components/settingPublicView/navList.js';
import { cloneDeep } from 'lodash';
import { handleChangeUseDept, handleChooseUseDept } from '@src/modules/setting/serviceEvent/serviceEventTypeSetting/manage/components/ChooseTeamConfirmDialog/utils/fetchFun';
/* service */
import IMService from '@service/IMService';

export default {
  name: 'service-event-list',
  data() {
    return {
      serviceEventTypeList: [],
      maxEventTypeNum: 0, //  最大事件类型
      isAddEventTypeModal: false,
      loading: true
    };
  },
  computed: {
    imInitData() {
      return IMService.getIMInitData()
    },
    eventNav() {
      
      let newEventNav = cloneDeep(eventNav);
      
      // 未开启客户机器人
      if (!this.imInitData?.customerServiceRobot) {
        newEventNav.list = newEventNav.list.filter(nav => nav.type !== 'robotSetting')
      }
      
      // 未开启在线客服
      if (!IMService.getIMIsOpen()) {
        newEventNav.list = newEventNav.list.filter(nav => nav.type !== 'imSetting')
      }
      
      return newEventNav;
    },
    enableTypeNum() {
      return this.serviceEventTypeList.filter(item => item.enabled === 1).length;
    }
  },
  mounted() {
    // 初始化服务事件列表
    this.getServiceEventList();
    // 修改标题
    if (window.frameElement) {
      const currentTabId = window.frameElement.dataset.id;
      let title = this.$t('event.setting.serviceEventTypeSetting.manage.title1')
      this.$platform.setTabTitle({
        id: currentTabId,
        title
      })
    }
  },
  methods: {
    handleChooseUseDept(item) {
      handleChooseUseDept.call(this, item, 'event')
    },
    async handleChangeUseDept(params) {
      try {
        await handleChangeUseDept(params, 'event')
      } catch(e) {
        console.error('【handleChangeUseDept error】', e)
      }
      // 列表接口调用数据有延时 --延迟刷新
      setTimeout(()=> this.getServiceEventList(), 500)
    },
    updateEventItemType(updateObj, evnetTypeItem) {
      for (const key in updateObj) {
        if (updateObj.hasOwnProperty(key)) {
          evnetTypeItem[key] = updateObj[key];
        }
      }
    },
    /** 获取服务事件列表*/
    async getServiceEventList() {
      try {
        const { status, data } = await getEventTypeList();
        const { maxEventTypeNum = 0, eventTypeList = []} = data;
        if(status == 0) {
          this.serviceEventTypeList = eventTypeList;
          this.maxEventTypeNum = maxEventTypeNum;
          this.loading = false;
        }
      } catch (e) {
        this.loading = false;
        console.error('error ', e)
      }
    },

    /** 新建事件类型操作*/
    addEventType() {
      // if(this.enableTypeNum >= this.maxEventTypeNum) return this.$message.warning(`最多只能同时存在${this.maxEventTypeNum}种事件类型`)
  
      this.isAddEventTypeModal = true;
    },

    /** 更新列表排序*/
    async updateListOrder() {
      let orderParams = {};
      this.serviceEventTypeList.map((typeItem, idx) => {
        if (!orderParams[typeItem.id]) orderParams[typeItem.id] = idx + 1;
        return {
          id: typeItem.id,
          order: idx + 1,
        };
      });
      const res = await orderWithEventTypeList(orderParams);
      if (res.status == 0) {
        // this.$message.success('事件排序成功');
      }
    },
  },
  components: {
    draggable,
    SettingPublicView,
    ServiceEventItem,
    [AddServiceEventDialog.name]: AddServiceEventDialog,
    [ChooseTeamConfirmDialog.name]: ChooseTeamConfirmDialog
  },
};
</script>

<style lang="scss" scoped>
.service-event-container {
  height: 100%;
  overflow: hidden;
  width: 100%;
  .service-event-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
    padding: 16px 16px 0 16px;
    width: 100%;
    background: #ffffff;
    border-radius: 4px;
    .el-icon-question {
      color: #666666;
    }
    h2 {
      margin-bottom: 10px;
      font-size: 16px;
      color: #333333;
      line-height: 22px;
    }
    p {
      font-size: 12px;
      color: #666666;
      line-height: 20px;
    }
    .lh-52 {
      line-height: 52px;
    }
  }

  .service-event-list {
    height: calc(100% - 100px);
    overflow: auto;
    .service-event-group {
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      // overflow: auto;
      @include dynamic-card-list(2, 'service-event-item');
      .service-event-item {
        margin: 0 12px 12px 0;
        // display: inline-block;
      }
    }
  }
}
</style>
